package com.yunyouyi.cpicture.infrastructure.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.yunyouyi.cpicture.infrastructure.exception.BusinessException;
import com.yunyouyi.cpicture.infrastructure.exception.ErrorCode;
import com.yunyouyi.cpicture.infrastructure.exception.ThrowUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

@Service
public class UrlPictureUpload extends PictureUploadTemplet {
    @Override
    protected void processFile(Object inputSource, File file) {
        String fileUrl = (String)inputSource;
        //下载文件到临时目录
        HttpUtil.downloadFile(fileUrl,file);
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        String fileUrl = (String)inputSource;
        return FileUtil.mainName(fileUrl);
    }

    @Override
    protected void validPicture(Object inputSource) {
        String fileUrl = (String)inputSource;
        //校验非空
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR,"地址为空");
        //校验url格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件地址格式错误");
        }
        //检验url协议
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"),
                ErrorCode.PARAMS_ERROR,"文件地址协议错误");
        //发送head请求获取文件信息
        try(HttpResponse httpResponse = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();/*//?*/){
            if (httpResponse.getStatus() != HttpStatus.SC_OK){
                return;
            }
            //进行文件校验
            String contentType = httpResponse.header("Content-Type");
            if(contentType != null){
                final List<String> ALLOW_CONTENT_TYPE = List.of("image/jpeg", "image/png", "image/gif","image/jpg");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPE.contains(contentType),ErrorCode.PARAMS_ERROR,"文件类型错误或不支持");
            }
            //文件大小
            String contentLength = httpResponse.header("Content-Length");
            if(contentLength != null){
                long fileSize = Long.parseLong(contentLength);
                ThrowUtils.throwIf(fileSize > 1024 * 1024 * 4,ErrorCode.PARAMS_ERROR,"文件大小不能超过4M");
            }
        }
    }
}
